
package com.hanhai.zrb.api.biz.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.hanhai.common.bizInterface.ChangeNotifyUtil;
import com.hanhai.zrb.api.biz.dao.mybatis.SysConfigDao;
import com.hanhai.zrb.api.biz.service.SysConfigService;
import com.hanhai.zrb.model.common.SysConfig;
import com.hanhai.zrb.model.common.SysConfig.ConfigKeyEnum;

@Service("sysConfigService")
public class SysConfigServiceImpl implements SysConfigService {

	private Map<String, String> map = new HashMap<String, String>();

	@Resource
	private SysConfigDao sysConfigDao;

	@PostConstruct
	void init() {
		List<SysConfig> sysConfigList = this.queryAll();
		for (SysConfig sysConfig : sysConfigList) {
			map.put(sysConfig.getSyskey(), sysConfig.getValue());
		}
	}

	private void notifySysConfigChange() {
		ChangeNotifyUtil.notify(SysConfigService.notifySubject,"all");
	}

	@Override
	public List<SysConfig> queryAll() {
		return sysConfigDao.getAll();
	}

	@Override
	public SysConfig getByKey(ConfigKeyEnum configKey) {
		return sysConfigDao.getByKey(configKey.name());
	}

	@Override
	public void save(SysConfig sysConfig) {
		sysConfigDao.save(sysConfig);
	}

	@Scheduled(cron = "0 0/1 * * * ? ")
	// 每5分钟一次
	@Override
	public void refresh() {
		init();
		notifySysConfigChange();
	}

	@Override
	public String getValueByKey(ConfigKeyEnum configKey) {
		SysConfig sysConfig = getByKey(configKey);
		if (sysConfig != null) {
			return sysConfig.getValue();
		} else {
			return null;
		}
	}

	@Override
	public String getValueFromLocalCache(ConfigKeyEnum configKey) {
		return map.get(configKey.name());
	}

}
